package com.heima.leetcode.datastructure.hashtable;

import java.util.*;

/**
 * <strong>找出文本中最多的单词 819</strong>
 * @author 勾新杰
 * @version 1.0
 * @date 2024/9/28 10:07
 */
public class MostCommonWord {

    /**
     * <h3>方法一</h3>
     * 使用正则表达式分割字符串，并用stream流遍历键值对集合
     * @param paragraph 文本
     * @param banned 禁用词
     * @return 出现最多的单词
     */
    public static String mostCommonWord1(String paragraph, String[] banned) {
        String[] split = paragraph.toLowerCase().split("[^a-zA-Z]+");
        Set<String> set = Set.of(banned);
        HashMap<String, Integer> map = new HashMap<>();
        for (String s : split) {
            if (!set.contains(s)){
                map.compute(s, (k, v) -> v == null ? 1 : v + 1);
            }
        }
        return map.entrySet().stream().max(Comparator.comparingInt(Map.Entry::getValue)).map(Map.Entry::getKey).orElse(null); // 如果没找到返回null
    }

    /**
     * <h3>方法二</h3>
     * 自己截取字符串和遍历键值对集合
     * @param paragraph 文本
     * @param banned 禁用词
     * @return 出现最多的单词
     */
    public static String mostCommonWord2(String paragraph, String[] banned) {
        Set<String> set = Set.of(banned);
        HashMap<String, Integer> map = new HashMap<>();
        StringBuilder builder = new StringBuilder();
        paragraph = paragraph + " ";
        for (char c : paragraph.toLowerCase().toCharArray()) {
            if (c >= 'a' && c <= 'z'){
                builder.append(c);
            }else{
                String key = builder.toString();
                if (!key.isEmpty() && !set.contains(key)){
                    // 修改对应键值
                    map.compute(key, (k, v) -> v == null ? 1 : v + 1);
                }
                builder.setLength(0);
            }
        }
        String maxKey = null;
        Integer maxValue = 0;
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            Integer value = entry.getValue();
            if (value > maxValue){
                maxKey = entry.getKey();
                maxValue = value;
            }
        }
        return maxKey;
    }
}
